package com.jmcgg.freesky.common.util;

/**
 * Title: FreeSky Common Java Library <br>
 * Description: FreeSky Common Java Library <br>
 * Copyright: Copyright (c) 2005~2009 www.afss.cn <br>
 * Company: Amei's FreeSky Studio <br>
 * 
 * @author <b>Jacky Chou</b> (AFSS [Amei's FreeSky Studio])
 * @version 1.2.1, 2008-08-05, Clean and optimize the source code.<br>
 *          1.2.0, 2008-02-23, Upgrade freesky.jar to 1.2.0 with Struts 2<br>
 *          1.0.0, 2006-05-30, Initial Version
 */

public class CodeUtil extends FreeskyUtil {
	public CodeUtil() {
	}

	/**
	 * 把str用(ISO8859-1)的编码格式 得到byte[] 转化为默认编码方式（unicode）
	 */
	public static String codeISO2Uni(String str) {
		if (str == null)
			return null;
		try {
			String tempStr = str;
			byte[] tempByte = tempStr.getBytes("ISO8859-1");
			String temp = new String(tempByte);
			return temp;
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 把str用(GB2312)的编码格式 得到byte[] 转化为默认编码方式（unicode）
	 */
	public static String codeGB2Uni(String str) {
		if (str == null)
			return null;
		try {
			String tempStr = str;
			byte[] tempByte = tempStr.getBytes("gb2312");
			String temp = new String(tempByte);
			return temp;
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 把str（unicode）转化为 （ISO8859-1）格式的编码
	 */
	public static String codeUni2ISO(String str) {
		if (str == null)
			return null;
		try {
			byte[] tempByte = str.getBytes();
			String temp = new String(tempByte, "ISO8859-1");
			return temp;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 把str（unicode）转化为 gb2312
	 */
	public static String codeUni2GB2312(String str) {
		if (str == null)
			return null;
		try {
			byte[] tempByte = str.getBytes();
			String temp = new String(tempByte, "gb2312");
			return temp;
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 字符编码转换，主要就是转换“ " ”
	 * 
	 * @param str
	 * @return
	 */
	public static String convert2HTML(String str) {
		if (str == null) {
			return "";
		} else {
			str = str.replaceAll("\"", "&quot;");
		}
		return str;
	}

	/**
	 * 把单引号替换为\',用于数据库操作时转义
	 * 
	 * @param str
	 *            源字符串
	 * @return 转义后的字符串
	 */
	public static String transSingleQuotes(String str) {
		if (str == null)
			return null;
		StringBuffer buffer = new StringBuffer(str);
		int len = buffer.length();
		int index = buffer.indexOf("'");
		while (index >= 0) {
			buffer.insert(index, '\'');
			if (index < len)
				index = buffer.indexOf("'", index + 2);
			else
				break;
		}

		return buffer.toString();
	}

}
